﻿using ETWJ.DTO;
using ETWJ.Iservice;
using ETWJ.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ETWJ.Service
{
    public class ProductOrderService : CommonService<ProductOrder, ProductOrderDTO, MyDbContext>, IProductOrderService<ProductOrder, ProductOrderDTO>
    {
        /// <summary>
        /// 通过 订单id获取该订单下所有的商品
        /// </summary>
        /// <param name="orderId">订单id</param>
        /// <returns></returns>
        public async Task<List<AddOrderProductModel>> GetProductByOrderId(int orderId)
        {
            List<AddOrderProductModel> list = new List<AddOrderProductModel>();
            using (MyDbContext ctx = new MyDbContext())
            {
                BaseService<ProductOrder> bs = new BaseService<ProductOrder>(ctx);
                //await bs.GetAll().Where(e => e.OrderId == orderId).AsNoTracking().ForEachAsync(e=> {
                //    list.Add(AutoMapper.Mapper.Map<ProductOrderDTO>(e));
                //});

                await ctx.Set<ProductOrder>().Where(e => e.IsDeleted == 0 && e.OrderId == orderId)
                    .Join(ctx.Set<Product>().Where(e => e.IsDeleted == 0), l => l.ProductId, r => r.Id, (l, r) => new AddOrderProductModel
                    {
                        Id=l.ProductId,
                        ProductCode=r.ProductCode,
                        ProductName=r.Name,
                        Price=r.Price.ToString(),
                        Num=l.Num,
                        Type=r.Type
                    }).AsNoTracking().ForEachAsync(e=> {
                        list.Add(e);
                    });

                return list;
            }
        }

        public async Task<int> DeleteProByPrIdAndProCode(int productId,string orderCode)
        {
            using (MyDbContext ctx = new MyDbContext())
            {
               var data=  ctx.Set<ProductOrder>().Where(e => e.IsDeleted == 0 && e.OrderCode == orderCode && e.ProductId == productId);
                ctx.Set<ProductOrder>().RemoveRange(data);
                return await ctx.SaveChangesAsync();
            }
        }
    }
}
